<template>
  <div v-loading="loading">
    <el-row>
      <el-col :span="21">
        <el-button size="mini" :type="currentRole === '' ? 'primary' : ''" @click="handleSelect('')">全部</el-button>
        <el-button v-for="item in memberTypeData" :key="item.code" size="mini" :type="currentRole === item.code ? 'primary' : ''" @click="handleSelect(item.code)">{{ item.value }}</el-button>
      </el-col>
      <el-col :span="3" align="right">
        <el-button size="mini" type="primary" @click="showAddMemberDialog()"><i class="el-icon-plus el-icon--right" /> 添加人员</el-button>
      </el-col>
      <el-col :span="24" class="gl_my_10">
        <el-button style="width: 100%" @click="showInviteMemberDialog"><i class="el-icon-plus el-icon--right" /> 邀请人员</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="15">
      <template v-if="existentMemberData.length > 0">
        <el-col v-for="item in existentMemberData" :key="item.id" :span="8" class="gl_my_5">
          <el-card shadow="hover" :body-style="{ padding: '10px', position: 'relative' }">
            <el-row :gutter="10">
              <el-col :span="7" align="center">
                <show-avatar
                  :src="getStaticAvatarUrl(item.imagePath)"
                  width="76px"
                  height="76px"
                  shape="circle"
                />
              </el-col>
              <el-col :span="17">
                <p class="gl_ft_weight" style="height: 18px;">{{ item.name }}</p>
                <div class="gl_mb_5 gl_ellipsis">
                  <span class="label_name">证件类型：</span>
                  <span class="label_content">{{ item.idCardType && item.idCardType.name }}</span>
                </div>
                <div class="gl_mb_5 gl_ellipsis">
                  <span class="label_name">证件号：</span>
                  <span class="label_content">{{ item.idCardNumber }}</span>
                </div>
                <div class="gl_mb_5 gl_ellipsis">
                  <span class="label_name">联系方式：</span>
                  <span class="label_content">{{ item.phoneNumber }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="5" type="flex" align="middle" style="height:75px ;">
              <el-col :span="13">
                <el-tag v-for="(tag, index) in item.registerTags" :key="tag.id" size="mini" class="gl_mr_5 gl_mt_5" :type="tagsColorTheme[index]" :disable-transitions=" false">
                  {{ tag.registerTagType && tag.registerTagType.name || tag.registerTagTypeCode }}
                </el-tag>
              </el-col>
              <el-col :span="11">
                <div class="operate_bu" align="right">
                  <el-button size="mini" type="primary" @click="showAddMemberDialog(item)">编辑</el-button>
                  <el-button size="mini" @click="deleteMember(item)">删除</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </template>
      <el-col v-if="existentMemberData.length > 0" :span="24">
        <div align="center" class="gl_pt_10">
          <el-pagination :current-page="registerQO.Page" :page-size="registerQO.MaxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[9, 18, 27, 36]" @size-change="sizeChange" @current-change="pageIndexChange" />
        </div>
      </el-col>
      <el-col v-else :span="24">
        <div class="gl_noData">
          <p>暂无数据</p>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="邀请人员" width="1100px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogInviteMember">
      <div v-loading="dialogLoading">
        <el-row :gutter="15">
          <el-col :span="5">
            <el-select v-model="registerByIdCardQO.idCardCode" placeholder="请选择证件类型" size="mini" style="width: 100%;">
              <el-option v-for="item in dict.idCardType" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-input v-model.trim="registerByIdCardQO.idCardNumber" clearable placeholder="请输入被邀请人证件号码" size="mini" />
          </el-col>
          <el-col :span="5">
            <el-input v-model.trim="registerByIdCardQO.name" clearable placeholder="请输入被邀请人姓名" size="mini" />
          </el-col>
          <el-col :span="9" class="search_btn">
            <el-button type="primary" size="mini" @click="getCanInviteMemberList()">{{ $t('button.query') }}</el-button>
            <el-button type="warning" size="mini" @click="resetRegisterByIdCardQO()">{{ $t('button.Reset') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col v-for="(item, index) in nonexistentMemberData" :key="index" :span="8" class="gl_mt_10">
            <el-card shadow="hover" :body-style="{ padding: '10px', position: 'relative' }">
              <el-row :gutter="10">
                <el-col :span="7" align="center">
                  <show-avatar
                    :src="getStaticAvatarUrl(item.imagePath)"
                    width="76px"
                    height="76px"
                    shape="circle"
                  />
                </el-col>
                <el-col :span="17">
                  <p class="gl_ft_weight" style="height: 18px;">{{ item.name }}</p>
                  <div class="gl_mb_5 gl_ellipsis">
                    <span class="label_name">证件类型：</span>
                    <span class="label_content">{{ item.idCardType && item.idCardType.name }}</span>
                  </div>
                  <div class="gl_mb_5 gl_ellipsis">
                    <span class="label_name">证件号：</span>
                    <span class="label_content">{{ item.idCardNumber }}</span>
                  </div>
                  <div class="gl_mb_5 gl_ellipsis">
                    <span class="label_name">联系方式：</span>
                    <span class="label_content">{{ item.phoneNumber }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10" type="flex" align="bottom" style="min-height: 50px;">
                <el-col :span="13">
                  <el-tag v-for="(tag, jndex) in item.registerTags" :key="tag.id" size="mini" class="gl_mr_5 gl_mt_5" :type="tagsColorTheme[jndex]" :disable-transitions=" false">
                    {{ tag.registerTagType && tag.registerTagType.name || tag.registerTagTypeCode }}
                  </el-tag>
                </el-col>
                <el-col :span="11">
                  <div class="operate_bu" align="right">
                    <el-button size="mini" @click="handleSubmitInviteOrgan(item)">邀请加入</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <el-col :span="24">
            <div v-if="nonexistentMemberData.length === 0" class="gl_noData">
              <p>暂无数据</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog class="gl_dialog_TitleLine" :title="editPersonalTitle" :visible.sync="dialogVisibleForPersonal" :close-on-click-modal="false" width="1200px">
      <div v-loading="dialogVisibleForPersonalLoading" class="gl_px_10">
        <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :is-default-check="!!(memberInfo && memberInfo.isApproved)" :is-show-tag="true" />
        <div slot="footer" align="right">
          <el-button size="mini" @click="dialogVisibleForPersonal = false">{{ $t('button.cancel') }}</el-button>
          <el-button size="mini" type="primary" :loading="memberLoading" @click="submitPersonalInfo">{{ $t('button.submit') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { translateByCode } from '@/lib/getTransData';
import {
  Api_GET_EventsManagementRegisterQO,
  SiSTKWEventsManagementCreateDelegationInput,
  SiSTKWEventsManagementCreateDelegationEntryInput,
  SiSTKWEventsManagementCreateRegisterWithTagsInput,
  Api_GET_EventsManagementRegisterByIdCardQO
} from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementRegister,
  api_POST_EventsManagementDelegationInviteRegisterRegisterId,
  api_POST_EventsManagementRegisterImport,
  api_POST_EventsManagementUserVerifyIdCardRegisterId,
  api_DELETE_EventsManagementDelegationRegisterRegisterId,
  api_POST_EventsManagementRegisterWithtags,
  api_GET_EventsManagementRegisterId,
  api_GET_EventsManagementRegisterTag,
  api_GET_EventsManagementRegisterByIdCard
} from '@/extend/api/gameswaggerApi/app';
import personalInfo from '@/components/PersonalInfo';
import { CopyData } from '@/lib';

export default {
  components: {
    personalInfo
  },
  data() {
    return {
      memberTypeData: [],
      currentRole: '',
      registerQO: new Api_GET_EventsManagementRegisterQO(),
      registerByIdCardQO: new Api_GET_EventsManagementRegisterByIdCardQO(),
      dialogInviteMember: false,
      createDelegationInput: new SiSTKWEventsManagementCreateDelegationInput(),
      existentMemberData: [],
      nonexistentMemberData: [],
      SiSTKWEventsManagementCreateDelegationEntryInput: new SiSTKWEventsManagementCreateDelegationEntryInput(),
      action: `${WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE}/api/app/events-management/register/import`,
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterWithTagsInput(),
      totalPage: 0,
      loading: false,
      dialogLoading: false,
      submitLoading: false,
      delegationId: '',
      /* 人员新增相关 */
      memberInfo: null,
      dialogVisibleForPersonalLoading: false,
      dialogVisibleForPersonal: false,
      editPersonalTitle: '',
      tagsColorTheme: ['primary', 'success', 'info', 'warning'],
      memberLoading: false
    };
  },
  computed: {
    ...mapState({
      currentUserType: state => state.user.currentUserType,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    'currentUserType': {
      handler: function(val) {
        if (val && val.delegationId) {
          this.delegationId = val.delegationId;
          this.handleSelect(this.$route.query.role || '');
        }
      },
      immediate: true
    }
  },
  created() {
    this.registerQO.MaxResultCount = 9;
    this.registerByIdCardQO.MaxResultCount = 9;
    this.getDict().then(res => {
      this.memberTypeData = res.registerTagType;
    });
    this.getDictByType(['district']);
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    handleSelect(code) {
      this.currentRole = code;
      this.getDataPage();
    },
    // 获取团体下的人员
    getDataPage(page) {
      if (!this.currentUserType.delegationId) return;
      this.loading = true;
      this.registerQO.Page = page || 1;
      this.registerQO.SkipCount = (this.registerQO.Page - 1) * this.registerQO.MaxResultCount;
      this.registerQO.IsApproved = null;
      this.registerQO.DelegationId = this.currentUserType.delegationId; // 传id获取当前团体下的人员，不传id获取的暂未加入任何团体的人员
      this.registerQO.RegisterTags = this.currentRole || [];
      this.registerQO.IncludeTags = true;
      this.registerQO.IncludeRegisterType = true;
      this.registerQO.IncludeIdCardType = true;
      api_GET_EventsManagementRegister(this.registerQO).then(res => {
        this.existentMemberData = res.items;
        this.totalPage = res.totalCount;
        this.loading = false;
      });
    },
    sizeChange(MaxResultCount) {
      this.registerQO.MaxResultCount = MaxResultCount;
      this.getDataPage();
    },
    pageIndexChange(currentPage) {
      this.getDataPage(currentPage);
    },
    // 邀请人员
    showInviteMemberDialog() {
      this.resetRegisterByIdCardQO();
      this.dialogInviteMember = true;
    },
    resetRegisterByIdCardQO() {
      this.registerByIdCardQO = new Api_GET_EventsManagementRegisterByIdCardQO();
      this.nonexistentMemberData = [];
    },
    // 添加人员 / 编辑人员
    showAddMemberDialog(personInfo) {
      this.editPersonalTitle = '新增';
      this.memberInfo = null;
      this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      if (personInfo) {
        this.editPersonalTitle = '编辑';
        this.dialogVisibleForPersonalLoading = true;
        this.getMemberInfo(personInfo.id).then(res => {
          this.dialogVisibleForPersonalLoading = false;
          this.memberInfo = res;
          this.memberInfo.registerTags = this.memberInfo.registerTags.map(item => item.registerTagTypeCode);
          CopyData(this.memberInfo, this.createRegisterInput);
        }, () => {
          this.dialogVisibleForPersonalLoading = false;
        });
      }
      this.dialogVisibleForPersonal = true;
      this.$nextTick(() => {
        this.$refs.refPersonalInfo.init();
      });
    },
    // 获取人员信息
    getMemberInfo(id) {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterId(id, { IncludeTags: true }).then(res => {
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        });
      });
    },
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData().then(res => {
        this.addMember(res);
      });
    },
    // 添加人员
    addMember(memberInfo) {
      this.memberLoading = true;
      memberInfo.registerTypeCode = 'I';
      memberInfo.isCurrentUser = false;
      memberInfo.joinCurrentDelegation = true;
      api_POST_EventsManagementRegisterWithtags(memberInfo).then(() => {
        this.memberLoading = false;
        this.$message({ type: 'success', message: this.memberInfo ? '编辑成功' : '新增成功' });
        this.getDataPage();
        this.dialogVisibleForPersonal = false;
        // 判断当前更改的为当前用户
        if (this.memberInfo.id === this.currentUserType.registerId) {
          this.getCurrentInfo();
          this.getTagList();
        }
      }, error => {
        this.memberLoading = false;
        this.$message({ type: 'error', message: (error.error && error.error.message || '') });
      });
    },
    getCurrentInfo() {
      if (!this.currentUserType.registerId) return;
      this.personInfoLoading = true;
      api_GET_EventsManagementRegisterId(
        this.currentUserType.registerId,
        { IncludeGender: true, IncludeIdCardType: true }
      ).then(res => {
        this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
      });
    },
    // 获取个人标签
    getTagList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterTag({
          RegisterId: this.currentUserType.registerId,
          IncludeRegisterTagType: true
        }).then(res => {
          this.$store.dispatch('user/getSaveCurrentUserTags', this.tagList);
        });
      });
    },
    // 删除会员
    deleteMember(memberInfo) {
      this.$confirm(`您确定要删除会员[ ${memberInfo.name} ]吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true;
        api_DELETE_EventsManagementDelegationRegisterRegisterId(memberInfo.id).then(res => {
          this.getDataPage();
          this.$message({ type: 'success', message: '操作成功' });
        }, error => {
          this.loading = false;
          this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        });
      });
    },
    // 获取可以邀请的人员列表
    getCanInviteMemberList() {
      this.dialogLoading = true;
      this.registerByIdCardQO.IncludeIdCardType = true;
      this.registerByIdCardQO.IncludeTags = true;
      api_GET_EventsManagementRegisterByIdCard(this.registerByIdCardQO).then(res => {
        this.nonexistentMemberData = res && [res] || [];
        this.dialogLoading = false;
        this.$message({ type: 'success', message: this.nonexistentMemberData.length ? '查询成功' : '查无此人' });
      }, error => {
        this.dialogLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    dialogSizeChange(MaxResultCount) {
      this.registerQO2.MaxResultCount = MaxResultCount;
      this.getOrganData();
    },
    dialogPageIndexChange(currentPage) {
      this.getOrganData(currentPage);
    },
    // 邀请加入团体
    handleSubmitInviteOrgan(row) {
      api_POST_EventsManagementDelegationInviteRegisterRegisterId(row.id).then(res => {
        this.getDataPage(this.registerQO.Page);
        this.resetRegisterByIdCardQO();
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message || '') });
      });
    },
    // 实名认证
    handleSubmitVerifyIdCard(row) {
      this.submitLoading = true;
      api_POST_EventsManagementUserVerifyIdCardRegisterId(row.id).then(valid => {
        this.submitLoading = false;
        if (valid) {
          this.getDataPage(this.registerQO.Page);
          this.$message({ type: 'success', message: '实名认证成功' });
        } else {
          this.$message({ type: 'error', message: '实名认证失败' });
        }
      });
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 2MB!');
        return false;
      }
      this.file = file;
    },
    upload() {
      this.submitLoading = true;
      const form = new FormData();
      form.append('formFile', this.file);
      api_POST_EventsManagementRegisterImport(form).then(res => {
        this.submitLoading = false;
        this.$message({ type: 'success', message: '操作成功' });
        this.getDataPage();
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    // 头像回显
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    getStaticUrl(relativeUrl) {
      return WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE + relativeUrl;
    }
  }
};
</script>
<style scoped>
.label_name {
  font-size: 14px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.8);
}
.label_content {
  color: #333;
  font-size: 14px;
}
</style>
